<template>
    <el-row class="block">
        <div style="width:350px" class="devInfo mini-form">
            <el-form label-width="100px" size="mini">
                <el-form-item label="" class="mt5">
                    <el-button type="primary" @click="getDeviceInfo" size="mini">读取设备信息</el-button>
                </el-form-item>
                <el-form-item label="设备" class="mt5">
                    <exSelect v-model="device" label="" :dictList="deviceList" size="mini" elstyle="width:170px" @change="changeDev"></exSelect>
                    
                </el-form-item>
                <el-form-item label="连接状态" class="mt5">
                    {{statusMap[connectStatus]}}
                </el-form-item>
                <el-form-item label="设备尺寸" class="mt5">
                    {{devInfo.devWidth}}*{{devInfo.devHeight}}
                </el-form-item>
                <el-form-item label="自动刷新屏幕" class="mt5">
                    <exSwitch v-model="aotoQry"></exSwitch>
                    (已连接状态下每{{waitTime}}秒更新)
                </el-form-item>
                <el-form-item label="同步点击事件" class="mt5">
                    <exSwitch v-model="asyncClick"></exSwitch>
                    (左键)
                </el-form-item>
                <el-form-item label="同步录制指令" class="mt5">
                    <exSwitch v-model="asyncRecordCmd"></exSwitch>
                    (左键)
                </el-form-item>
                <el-form-item label="左键的坐标" class="mt5">
                    <el-row>
                        {{devInfo.clickX}}*{{devInfo.clickY}}
                        转换后
                        {{realX | fixed}}*{{realY | fixed}}
                    </el-row>
                    <el-row>
                        颜色: {{devInfo.color}}
                        <canvasCmp :colors="devInfo.color" type="point"></canvasCmp>
                    </el-row>
                </el-form-item>
                <el-form-item label="右键的坐标" class="mt5">
                    <el-row>
                        {{devInfo.clickRX}}*{{devInfo.clickRY}}
                        转换后
                        {{realRX | fixed}}*{{realRY | fixed}}
                    </el-row>
                    <el-row>
                        颜色: {{devInfo.rcolor}}
                        <canvasCmp :colors="devInfo.rcolor" type="point"></canvasCmp>
                    </el-row>
                </el-form-item>
                <el-form-item label="颜色线" class="mt5">
                    <span style="word-break: break-all;display:inline-block;max-width:90%;max-height:80px;overflow-y:auto">
                        <span v-if="devInfo.colors">({{devInfo.colors.length}}组)</span> {{devInfo.colors}}
                    </span>
                    <el-row>
                        <canvasCmp :colors="devInfo.colors" type="line"></canvasCmp>
                    </el-row>
                </el-form-item>
                <el-form-item label="颜色块" class="mt5">
                    <span style="word-break: break-all;display:inline-block;max-width:90%;max-height:80px;overflow-y:auto">
                        <span v-if="devInfo.rectcolors">({{devInfo.rectcolors.length}}组)</span>
                    </span>
                    <el-row>
                        宽度: {{devInfo.rectcolorswidth}} 
                        高度: {{devInfo.rectcolorsheight}}
                        <!-- <canvasCmp :colors="devInfo.rectcolors" :rectWidth="devInfo.rectcolorswidth" :rectHeight="devInfo.rectcolorsheight" type="rect"></canvasCmp> -->
                    </el-row>
                </el-form-item>
                <el-form-item label="当前应用" class="mt5">
                    <span style="word-break: break-all;display:inline-block;max-width:90%">{{devInfo.curApp}}</span>
                </el-form-item>
                <!-- <el-form-item label="当前画面1" class="mt5">
                    <span style="word-break: break-all;display:inline-block;max-width:90%">{{devInfo.curImg}}</span>
                </el-form-item>
                <el-form-item label="当前应用2" class="mt5">
                    <span style="word-break: break-all;display:inline-block;max-width:90%">{{devInfo.curAppRnd}}</span>
                </el-form-item> -->
                <el-form-item label="手机按键" class="mt5">
                    <el-link type="primary" @click="doDevKeyEvent(3)">HOME</el-link>
                    <el-link type="primary" class="ml10" @click="doDevKeyEvent(4)">BACK</el-link>
                    <el-link type="primary" class="ml10" @click="setRandom">rnd</el-link>
                </el-form-item>
            </el-form>
            
        </div>
        <div style="width:320px" class="devImg">
            <div :style="imgStyle" style="border: 0px red solid;margin:auto;position:relative;box-shadow: 5px 5px 25px #888888;">
                <div v-if="connectStatus==1 && devInfo.clickX>0" style="position:absolute;width:4px;height:4px;border-radius:4px;background:red;z-index:10;pointer-events: none;" 
                    :style="{top:(devInfo.clickY)+'px',left:(devInfo.clickX)+'px'}"></div>
                <div v-if="connectStatus==1 && devInfo.clickRX>0" style="position:absolute;width:4px;height:4px;border-radius:4px;background:blue;z-index:10;pointer-events: none;" 
                    :style="{top:(devInfo.clickRY)+'px',left:(devInfo.clickRX)+'px'}"></div>
                <!-- <el-image :style="imgStyle" :src="'/img/screenshot.png?'+random" fit="contain" 
                    @click="setClickPoint" @contextmenu="setRightClickPoint">
                
                </el-image> -->
                <canvas ref="canvasEl" :style="imgStyle" v-if="isShowCanvas"  @contextmenu="setRightClickPoint"></canvas>
            </div>
        </div>
        <div style="min-width:950px;padding-right:20px" class="pl10 pt10">
            <el-row style="border-bottom: 1px gray dotted;padding-bottom:10px">
                指令组: 
                <exSelect v-model="selGroup" :dictList="cmdList" @change="onChangeSelGroup" size="mini" elstyle="width:140px"></exSelect>
                <exInput v-model="selGroupInfo.name" label="组名" size="mini" width="100"></exInput>
                <el-button size="mini" type="primary" @click="addGroup()">增加</el-button>
                <el-button size="mini" type="primary" @click="delGroup()">删除</el-button>
                <el-button size="mini" type="primary" @click="setDefGroup()">设为默认</el-button>
                <!-- <el-button size="mini" type="primary" @click="addCmd()">保存</el-button> -->

                <el-button size="mini" type="warning" @click="saveConfig" style="float:right" class="mr10">保存指令</el-button>
            </el-row>
            <el-row class="mt5" v-if="selGroupInfo.value">
                <el-button size="mini" type="primary" @click="addCmd()" :title="`执行次数: ${tmpCount}`">增加指令</el-button>
                <el-button size="mini" type="success" v-if="runIdx==-2" @click="runCmd()">执行指令</el-button>
                <el-button size="mini" type="warning" v-else @click="stopCmd()">中断指令</el-button>
                

                <el-popover placement="bottom" width="360" trigger="click" style="float:right" class="mr10">
                    <exInput v-model="importTxt" type="textarea" :rows="10" width="350"></exInput>
                    <div style="text-align: right;" class="mt10">
                        <el-button type="primary" size="mini" @click="doImport">导入</el-button>
                    </div>
                    <el-button size="mini" type="success" slot="reference">导入指令</el-button>
                </el-popover>
                <el-button size="mini" type="success" @click="copyConfig" style="float:right" class="mr10">复制指令到剪切板</el-button>

                
            </el-row>
            <el-row style="overflow-y:auto;max-height:600px;" >
                <div :style="cmdListStyle" ref="cmdListDiv">
                    <template v-if="isShowCmds">
                        <cmditem v-for="(item,idx) in selGroupInfo.cmds" :key="idx" :cmdInfo="item" :cmdIdx="idx"
                            :devInfo="devInfo" :ref="'cmd'+idx" @delCmd="delCmd" @changeLevel="changeLevel"></cmditem>
                    </template>
                </div>
            </el-row>
        </div>
    </el-row>
</template>


<script>

import cmditem from "./cmd/cmditem"
import canvasCmp from "./cmd/util/canvasCmp.vue"

export default {
    components:{
        cmditem,
        canvasCmp
    },
    props:["deviceList"],
    watch:{
        deviceList(){
            this.device = "";
            this.deviceList.map(item=>{
                if(!this.device && item.isAuth) this.device = item.value;
            })
            this.changeDev();
        }
    },
    data() {
        return {
            isShowCanvas : true,
            device:this.deviceList[0]?this.deviceList[0].value:"",
            connectStatus: 0,
            statusMap:{
                0: "未连接",
                1: "已连接",
                2: "连接失败",
            },
            devInfo:{
                devWidth: 0,
                devHeight: 0,
                devBet : 0,
                clickX : 0,
                clickY : 0,
                color : [],
                clickRX : 0,
                clickRY : 0,
                rcolor : [],
                colors : [],
                rectcolors : [],
                rectcolorswidth: 1,
                rectcolorsheight: 1,
                curApp : "",
                curAppRnd : "",
                curImg : "",
            },
            random : "",
            aotoQry : false,
            asyncClick : false,
            asyncRecordCmd : false,
            waitTime : 3,
            tmpCount : 0,
            cmdList : [

            ],
            runIdx: -2,
            cfg: {},
            selGroup : "",
            defCmd : [
                {name:"小米有品-茅台",value:"234234234",cmds:[
                    {"type":"stopApp","appPath":"com.xiaomi.youpin","x1":0,"y1":0,"x2":0,"y2":0,children:[]},
                    {"type":"wait","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"waitTime":5,children:[]},
                    {"type":"openApp","appPath":"com.xiaomi.youpin","x1":0,"y1":0,"x2":0,"y2":0,children:[]},
                    {"type":"wait","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"waitTime":15,children:[]},
                    {"type":"click","appPath":"","x1":265,"y1":268,"x2":0,"y2":0,children:[]},
                    {"type":"wait","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"waitTime":15,children:[]},
                    {"type":"click","appPath":"","x1":154,"y1":125,"x2":0,"y2":0,children:[]},
                    {"type":"timer","appPath":"","x1":0,"y1":0,"x2":0,"y2":0,"timer":"09:59:45",children:[]},
                    {"type":"circle","appPath":"","x1":164,"y1":451,"x2":0,"y2":0,"waitTime":100,"keep":30,children:[]}
                ]},
            ],
            importTxt:"",
            isShowCmds: true,
            cmdListStyle : "",
        };
    },
     

    mounted() {
        this.devInfoBak = JSON.stringify(this.devInfo)
        this.regIpc();
        var that = this;
        var autoTimer = setInterval(()=>{
            if(!that.aotoQry) return;
            that.getDevPic();
        },this.waitTime*1000);
        this.$once('hook:beforeDestroy', () => {            
            clearInterval(autoTimer);                                    
        })
        this.readConfig()
    },
    computed:{
        showWidth(){
            var width = 300;
            return width;
        },
        showHeight(){
            var height = 400;
            if(this.devInfo.devWidth!=0){
                this.devInfo.devBet = this.devInfo.devWidth/this.showWidth;
                height = this.devInfo.devHeight /this.devInfo.devBet;
            }
            return height;
        },
        imgStyle(){
            return `height: ${this.showHeight}px;width:${this.showWidth}px;`;
        },
        realX(){
            return this.devInfo.clickX*this.devInfo.devBet
        },
        realY(){
            return this.devInfo.clickY*this.devInfo.devBet
        },
        realRX(){
            return this.devInfo.clickRX*this.devInfo.devBet
        },
        realRY(){
            return this.devInfo.clickRY*this.devInfo.devBet
        },
        selGroupInfo(){
            if(!this.selGroup) return {name:"",value:"",cmds:[]};
            var group =  this.cmdList.find((item)=>{ return item.value==this.selGroup})
            if(!group) return {name:"",value:"",cmds:[]};
            return group
        }
    },
    provide () {
      return {
        doDevCmd: this.doDevCmd,
        doNextCmd: this.runNextCmd,
        addCmd : this.addCmd,
        moveCmd : this.moveCmd,
        getImgData : this.getImgData,
        getDevPic : this.getDevPic,
        getCurApp : this.getCurApp,
        doDevKeyEvent: this.doDevKeyEvent
      }
    },

    methods: {
        onChangeSelGroup(){
            this.isShowCmds = false;
            this.cmdListStyle = this.$refs.cmdListDiv.clientHeight||"";
            this.$nextTick(()=>{
                this.cmdListStyle = "";
                this.isShowCmds = true;
            })
        },
        addGroup(){
            var id = parseInt(Math.random()*100000)+"";
            var group = {name:"新增",value:id,cmds:[]};
            this.selGroup = id;
            this.cmdList.push(group)
        },
        setDefGroup(){
            for(var i=0;i<this.cmdList.length;i++){
                var item = this.cmdList[i];
                if(item.value==this.selGroup){
                    item.isDef = true;
                }else{
                    item.isDef = false;
                }
            }
            this.$message.success("设置成功")
        },
        delGroup(){
            if(!this.selGroup){
                this.$message.error("请选择要删除的组")
                return;
            }
            this.$confirm('确认要删除选中的分组?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var that = this;
                for(var i=0;i<this.cmdList.length;i++){
                    var item = this.cmdList[i];
                    if(item.value==this.selGroup){
                        this.cmdList.splice(i,1);
                        this.selGroup="";
                        break;
                    }
                }
            });
        },
        doImport(){
            try{
                var list = JSON.parse(this.importTxt)
                if(list.length>0){
                    this.selGroupInfo.cmds = list;
                }
            }catch(ex){
                this.$message.error("导入异常:"+ex.message)
            }
        },
        updateCmds(){
            for(var i=0;i<this.selGroupInfo.cmds.length;i++){
                var el = this.$refs["cmd"+i];
                if(el){
                    el[0].saveCmd()
                }
            }
        },
        copyConfig(){
            this.updateCmds();
            this.copy(JSON.stringify(this.selGroupInfo.cmds))
        },
        saveConfig(){
            this.updateCmds();
            this.cfg.devCfg.cmdList = this.cmdList;

            this.$confirm('确认要保存记录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var that = this;
                
                this.registerListen(this,"saveConfig",(err)=>{
                    try{
                        if(err){
                            that.$message.error("配置保存异常:"+err)
                        }else{
                            that.$message.success("保存成功")
                        }
                    }catch(ex){
                            that.$message.error("配置保存异常:"+err)
                    }
                });
                
                electron.ipcRenderer.send("saveConfig",this.cfg)
            });
        },
        readConfig(){
            var that = this;
            if(!window.electron){
                return;
            }
            this.registerListen(this,"setConfig",(cfg)=>{
                try{
                    cfg.devCfg = cfg.devCfg || {};
                    cfg.devCfg.cmdList = cfg.devCfg.cmdList || that.defCmd;
                    if(cfg.devCfg.cmdList.length>0){
                        if(!cfg.devCfg.cmdList[0].value){
                            var item = {name:"默认分组",value:"defCmd",cmds:cfg.devCfg.cmdList};
                            cfg.devCfg.cmdList = [item]
                        }
                    }
                    that.cmdList = cfg.devCfg.cmdList;
                    if(that.cmdList.length>0){
                        var group = that.cmdList.find((item)=>{return item.isDef===true})
                        if(!group) that.selGroup = that.cmdList[0].value
                        else that.selGroup = group.value;
                        that.cmdList.map(item=>{
                            if(!item.children) item.children = []
                        })
                    }
                    that.cfg = cfg;
                }catch(ex){
                    that.$message.error("配置加载异常:"+ex.message)
                }
            });
            electron.ipcRenderer.send("getConfig","")

        },
        changeLevel(idx,isDown){
            if(idx==undefined) return;
            if(idx==0) return;
            if(isDown){
                if((this.selGroupInfo.cmds[idx].level+1)==this.selGroupInfo.cmds[idx-1].level){
                    this.selGroupInfo.cmds[idx].level+=1;
                }
            }else{
                if(this.selGroupInfo.cmds[idx].level>0){
                    if(idx==this.selGroupInfo.cmds.length-1 || 
                        (this.selGroupInfo.cmds[idx].level-1)==this.selGroupInfo.cmds[idx+1].level
                    ){
                        this.selGroupInfo.cmds[idx].level-=1;
                    }
                }
            }
            this.onChangeSelGroup();
            
        },
        runCmd(){
            for(var i=0;i<this.selGroupInfo.cmds.length;i++){
                var cmd = this.selGroupInfo.cmds[i];
                cmd.level= cmd.level || 0;
                var el = this.$refs["cmd"+i];
                if(el && el[0] && el[0].initCmd){
                    el[0].initCmd()
                }
            }
            this.runIdx++;
            this.runNextCmd();
        },
        runNextCmd(param={}){
            this.tmpCount = this.tmpCount||0;
            this.tmpCount++;
            // if(this.tmpCount>1000)return;

            var preCmd = this.selGroupInfo.cmds[this.runIdx] || {level:0};
            this.runIdx++;
            if(param.idx) this.runIdx = param.idx;
            if(this.runIdx<0){
                this.runIdx=-2;
                return;
            }
            if(this.runIdx==this.selGroupInfo.cmds.length){
                this.runIdx=-2;
                return;
            }
            
            var cmd = this.selGroupInfo.cmds[this.runIdx];
            if(param.level && param.limitLevel && param.level!=cmd.level){
                return;
            }
            if(param.continue){
                for(var i=this.runIdx-1;i>=0;i--){ //回头寻找父指令
                    cmd = this.selGroupInfo.cmds[i];
                    if(cmd.type=="for"){
                        this.runIdx = i;
                        break;
                    }
                }
            }else if(param.break){
                for(var i=this.runIdx-1;i>=0;i--){ //回头寻找父指令
                    cmd = this.selGroupInfo.cmds[i];
                    if(cmd.type=="for"){
                        this.runIdx = i;
                        var el = this.$refs["cmd"+i];
                        if(el && el[0] && el[0].initCmd){
                            el[0].initCmd()
                        }
                        break;
                    }
                }
                var preCmd = this.selGroupInfo.cmds[this.runIdx] || {level:0};
                this.runIdx++;
                for(var i=this.runIdx;i<this.selGroupInfo.cmds.length;i++){
                    cmd = this.selGroupInfo.cmds[i];
                    if(cmd.level<=preCmd.level){
                        this.runIdx = i;
                        break;
                    }
                }
            }else if(param.finish){
                for(var i=this.runIdx;i<this.selGroupInfo.cmds.length;i++){
                    cmd = this.selGroupInfo.cmds[i];
                    if(cmd.level<=preCmd.level){
                        this.runIdx = i;
                        break;
                    }
                }
            }else if(preCmd.level || cmd.level){  //子命令
                if(preCmd.level > cmd.level){  //子命令执行结束
                    for(var i=this.runIdx-1;i>=0;i--){ //回头寻找父指令
                        cmd = this.selGroupInfo.cmds[i];
                        if(cmd.level<preCmd.level){
                            this.runIdx = i;
                            break;
                        }
                    }
                }else if(preCmd.level < cmd.level){ //子命令开始执行

                }
            }

            this.$refs["cmd"+this.runIdx][0].runCmd()
        },
        stopCmd(){
            for(var i=0;i<this.selGroupInfo.cmds.length;i++){
                var el = this.$refs["cmd"+i];
                if(el){
                    el[0].stopCmd()
                }
            }
            this.runIdx=-2;
        },
        changeDev(){
            var tmp =JSON.parse(this.devInfoBak)
            Object.assign(this.devInfo,tmp)
            this.connectStatus = 0;
            if(this.device) this.getDeviceInfo();
        },
        moveCmd(idx,type){
            if(idx==0 && type==1) return;
            if(idx==this.selGroupInfo.cmds.length-1 && type==0) return;
            var len = 1;
            var curcmd = this.selGroupInfo.cmds[idx];
            for(var i=idx+1;i<this.selGroupInfo.cmds.length;i++){
                var item = this.selGroupInfo.cmds[i];
                if(item.level>curcmd.level){
                    len++;
                }else{
                    break;
                }
            }
            var tmplist = this.selGroupInfo.cmds.splice(idx,len);
            var tmpcmd = null;
            var tmpidx = idx;
            if(type==0){ //下降
                tmpcmd = this.selGroupInfo.cmds[idx]
                if(!tmpcmd || tmpcmd.level<curcmd.level){
                    tmplist.reverse();
                    tmplist.map(a=>{
                        this.selGroupInfo.cmds.splice(tmpidx,0,a);
                    })
                    return;
                }
                for(var i=idx+1;i<this.selGroupInfo.cmds.length;i++){
                    var item = this.selGroupInfo.cmds[i];
                    if(item.level>tmpcmd.level){
                        tmpidx++;
                    }else{
                        break;
                    }
                }
                if(tmpidx>=0){
                    tmplist.reverse();
                    tmplist.map(a=>{
                        this.selGroupInfo.cmds.splice(tmpidx+1,0,a);
                    })
                }
            }else{
                tmpcmd = this.selGroupInfo.cmds[idx-1]
                if(!tmpcmd || tmpcmd.level<curcmd.level){
                    tmplist.reverse();
                    tmplist.map(a=>{
                        this.selGroupInfo.cmds.splice(tmpidx,0,a);
                    })
                    return;
                }
                for(var i=idx-1;i>=0;i--){
                    var item = this.selGroupInfo.cmds[i];
                    if(item.level>curcmd.level){
                        tmpidx--;
                    }else{
                        break;
                    }
                }
                if(tmpidx>=0){
                    tmplist.reverse();
                    tmplist.map(a=>{
                        this.selGroupInfo.cmds.splice(tmpidx-1,0,a);
                    })
                }
            }
            
            // if(curcmd.level != tmpcmd.level) return;
            //     this.selGroupInfo.cmds.splice(idx,1);
            // if(type==0){ //下降
            //     this.selGroupInfo.cmds.splice(idx+1,0,curcmd);
            // }else{
            //     this.selGroupInfo.cmds.splice(idx-1,0,curcmd);
            // }
            this.onChangeSelGroup();
        },
        addCmd(cmd,idx){
            cmd = cmd || {type:"",level:0};
            cmd.level = cmd.level || 0;
            if(idx){
                for(var i=idx;i<this.selGroupInfo.cmds.length;i++){
                    var tmp = this.selGroupInfo.cmds[i];
                    if(tmp.level>=cmd.level){
                        idx++
                    }else{
                        break;
                    }
                }
                this.selGroupInfo.cmds.splice(idx,0,cmd)
            }else{
                this.selGroupInfo.cmds.push(cmd);
            }
        },
        delCmd(idx){
            var len = 1;
            var curcmd = this.selGroupInfo.cmds[idx];
            for(var i=idx+1;i<this.selGroupInfo.cmds.length;i++){
                var tmp = this.selGroupInfo.cmds[i];
                if(tmp.level>curcmd.level){
                    len++
                }else{
                    break;
                }
            }
            this.selGroupInfo.cmds.splice(idx,len)
            this.onChangeSelGroup();
        },
        setClickPoint(e,color){
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            this.devInfo.color = color || [];
            this.devInfo.clickX = e.layerX; 
            this.devInfo.clickY = e.layerY; 
            if(this.asyncRecordCmd){
                this.selGroupInfo.cmds.push({"type":"click","appPath":"","x1":this.devInfo.clickX,"y1":this.devInfo.clickY,"x2":0,"y2":0})
            }
            if(this.asyncClick){
                this.doDevClick(this.devInfo.clickX,this.devInfo.clickY);
            }
        },
        setRightClickPoint(e,isNew,color){
            if(!isNew) return;
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            this.devInfo.rcolor = color || [];
            this.devInfo.clickRX = e.layerX; 
            this.devInfo.clickRY = e.layerY; 
            if(this.asyncRecordCmd){
                this.selGroupInfo.cmds.push({"type":"click","appPath":"","x1":this.devInfo.clickRX,"y1":this.devInfo.clickRY,"x2":0,"y2":0})
            }
        },
        initCanvas(){
            var that = this;
            var el = this.$refs.canvasEl;
            el.height = that.showHeight;
            if(!el) return;
            var ctx = el.getContext('2d');
            ctx.strokeStyle = '#BADA55'; //ctx is the canvas
            ctx.lineJoin = 'round';
            ctx.lineCap = 'round';
            ctx.lineWidth = 1;
            that.canvasCtx =ctx;
            let isDrawing = false;
            var lineMap={
                x1:0,
                y1:0,
                c1:[],
                x2:0,
                y2:0,
                c2:[]
            }
            function draw(e) {
                if(Math.abs(lineMap.x1-lineMap.x2)<5 && Math.abs(lineMap.y1-lineMap.y2)<5){
                    if(e.button==0){
                        that.setClickPoint(e,lineMap.c1);
                    }else{
                        that.setRightClickPoint(e,true,lineMap.c2);
                    }
                    return;
                }
                that.$nextTick(()=>{
                    that.devInfo.clickX = lineMap.x1;
                    that.devInfo.clickY = lineMap.y1;
                    that.devInfo.color = lineMap.c1;
                    that.devInfo.clickRX = lineMap.x2;
                    that.devInfo.clickRY = lineMap.y2;
                    that.devInfo.rcolor = lineMap.c2;
                    var colorData = that.getImgData(lineMap.x1,lineMap.y1,lineMap.x2-lineMap.x1,lineMap.y2-lineMap.y1)
                    that.devInfo.colors = colorData || [];
                    if(that.asyncRecordCmd){
                        that.selGroupInfo.cmds.push({"type":"move","appPath":"",
                            "x1":that.devInfo.clickX,"y1":that.devInfo.clickY,"x2":that.devInfo.clickRX,"y2":that.devInfo.clickRY})
                    }

                    // setTimeout(()=>{
                    //     ctx.beginPath();
                    //     // start from
                    //     ctx.moveTo(lineMap.x1, lineMap.y1);
                    //     // go to
                    //     ctx.lineTo(lineMap.x2, lineMap.y2);
                    //     ctx.stroke();
                    // },300)
                })
                
            }
            el.addEventListener('mousedown', (e) => {
                var colorData = this.getImgData(e.offsetX,e.offsetY)
                lineMap={
                    x1:e.offsetX,
                    y1:e.offsetY,
                    c1:colorData,
                    x2:0,
                    y2:0
                }
            });
            // el.addEventListener('mousemove', draw);
            el.addEventListener('mouseup', (e) => {
                var colorData = this.getImgData(e.offsetX,e.offsetY)
                lineMap.x2=e.offsetX;
                lineMap.y2=e.offsetY;
                lineMap.c2=colorData;
                draw(e)
            });
            el.addEventListener('mouseout', () => isDrawing = false);
        },
        getImgData(x,y,width=1,height=1,getRect){
            var that = this;
            if(height<1) height = 1;
            if(width==0) return [];
            var imgData = that.canvasCtx.getImageData(x,y,width,1).data;
            var colorData = [];
            if(width==1){
                colorData = [imgData[0],imgData[1],imgData[2]];
            }else{
                if(getRect){
                    var rectcolors = []
                    var rectimgData = that.canvasCtx.getImageData(x,y,width,height).data;
                    that.devInfo.rectcolorswidth = width;
                    that.devInfo.rectcolorsheight = height;
                    var subarr = [];
                    rectimgData.map((item,idx)=>{
                        var mod = idx%4;
                        if(mod==0){
                            subarr = [];
                            subarr.push(item)
                        }else if(mod==1){
                            subarr.push(item)
                        }else if(mod==2){
                            subarr.push(item)
                        }else if(mod==3){
                            rectcolors.push(subarr)
                        }
                    })
                    that.devInfo.rectcolors = rectcolors;
                    return {
                        rectWidth : width,
                        rectHeight : height,
                        rectcolors : rectcolors,
                    };
                }
                var imgData = that.canvasCtx.getImageData(x,y,width,1).data;
                var subarr = [];
                imgData.map((item,idx)=>{
                    var mod = idx%4;
                    if(mod==0){
                        subarr = [];
                        subarr.push(item)
                    }else if(mod==1){
                        subarr.push(item)
                    }else if(mod==2){
                        subarr.push(item)
                    }else if(mod==3){
                        colorData.push(subarr)
                    }
                })
            }
            return colorData;
        },
        setRandom(){
            var that =this;
            this.random = Math.random();
            var src = `/img/screenshot.png?name=${this.device}&rnd=${this.random}`;
            if(!this.canvasCtx){
                this.initCanvas();
            }
            // ctx.setTransform(1, 0, 0, 1, 0, 0);
			var img = new Image();
			img.onload = ()=>{
                img.width = that.showWidth;
                img.height = that.showHeight;
                that.canvasCtx.drawImage(img,0,0,that.showWidth,that.showHeight)
                that.canvasCtx.save();
                that.devInfo.curImg = Math.random();
			}
			img.src = src;
        },
        getDeviceInfo(){
            this.devInfo.devWidth = 0;
            this.devInfo.devHeight = 0;
            this.connectStatus = 0;
            if(!this.device){
                this.$message.error("请先选择设备")
                return;
            }
            electron.ipcRenderer.send("doCmd",{name:"getWindowInfo",cmd:"adb shell dumpsys window displays",param:{type:"adb",devname:this.device}})
        },
        getCurApp(){
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            electron.ipcRenderer.send("doCmd",{name:"getCurApp",cmd:"adb shell dumpsys window",param:{type:"adb",devname:this.device}})
        
        },
        getDevPic(){
            var curtime = new Date().getTime();
            this.preGetPicTime = this.preGetPicTime || 0;
            if(curtime-this.preGetPicTime<1000){
                return;
            }
            this.preGetPicTime = curtime;
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            electron.ipcRenderer.send("doCmd",{name:"getDevPic",cmd:`adb shell /system/bin/screencap -p /sdcard/${this.device}.png&adb pull /sdcard/${this.device}.png D:/tmp/${this.device}.png`,param:{type:"adb",devname:this.device}})
        },
        doDevClick(clickX,clickY){
            if(!clickX || !clickY) return;
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            electron.ipcRenderer.send("doCmd",{name:"doDevCmd",cmd:`adb shell input tap ${clickX*this.devInfo.devBet} ${clickY*this.devInfo.devBet} `,param:{type:"adb",devname:this.device}})
            setTimeout(()=>{
                this.getDevPic();
            },500)
        },
        doDevCmd(cmd){
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            console.log("cmd: "+cmd)
            electron.ipcRenderer.send("doCmd",{name:"doDevCmd",cmd:cmd,param:{type:"adb",devname:this.device}})
        },
        doDevKeyEvent(key){
            if(this.connectStatus!=1) return;
            if(!this.device) return;
            if(!key) return;
            electron.ipcRenderer.send("doCmd",{name:"doDevCmd",cmd:`adb shell input keyevent ${key}`,param:{type:"adb",devname:this.device}})
            setTimeout(()=>{
                this.getDevPic();
            },500)
        },
        regIpc(){
            var that = this;
            if(!window.electron){
                return;
            }
            electron.ipcRenderer.send("doCmd",{name:"createDir",cmd:"md d:\\tmp"})
            this.registerListen(this,"getWindowInfo",(res)=>{
                try{
                    if(res.isSucc){
                        // that.$message.info(res.info);
                        var info = res.info.match(/cur=[0-9]*x[0-9]*/)
                        if(!info || info.length==0) return;
                        var arr = info[0].split(/=|x/);
                        that.connectStatus = 1;
                        that.devInfo.devWidth = arr[1];
                        that.devInfo.devHeight = arr[2];
                        // that.isShowCanvas = false;
                        that.$nextTick(()=>{
                            // that.isShowCanvas = true;
                            that.getDevPic();
                            that.getCurApp();
                            that.canvasCtx = null;
                            that.initCanvas();
                        })
                    }else{
                        that.connectStatus = 2;
                        that.$message.error("指令("+res.cmd+")执行异常:"+res.info)
                    }
                }catch(ex){
                    that.$message.error("指令执行异常:"+ex.message)
                }
            });
            this.registerListen(this,"getCurApp",(res)=>{
                try{
                    if(res.isSucc){
                        var pos = res.info.indexOf("mCurrentFocus");
                        if(pos!=-1){
                            var tmparr = res.info.match(/mCurrentFocus.*[}]/)
                            if(tmparr && tmparr.length>0){
                                tmparr = tmparr[0];
                                tmparr = tmparr.split(" ");
                                tmparr = tmparr[tmparr.length-1];
                                tmparr = tmparr.substring(0,tmparr.length-1);
                                that.devInfo.curApp = tmparr;
                                that.devInfo.curAppRnd = Math.random()
                            }
                        }
                    }else{
                        that.$message.error("指令("+res.cmd+")执行异常:"+res.info)
                    }
                }catch(ex){
                    that.$message.error("指令执行异常:"+ex.message)
                }
            });
            this.registerListen(this,"getDevPic",(res)=>{
                try{
                    if(res.isSucc){
                        that.setRandom();
                    }else{
                        that.$message.error("指令("+res.cmd+")执行异常:"+res.info)
                    }
                }catch(ex){
                    that.$message.error("指令执行异常:"+ex.message)
                }
            });
            this.registerListen(this,"doDevCmd",(res)=>{
                try{
                    if(!res.isSucc) that.$message.error("指令("+res.cmd+")执行异常:"+res.info)
                }catch(ex){
                    that.$message.error("指令执行异常:"+ex.message)
                }
            });
        },
    }
}
</script>

<style lang="less" scoped>

.block{
    min-height: 400px;
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    overflow-x: true;
    // border: 1px red solid;

    .devInfo{
        border-right: 1px gray dotted;
        height:100%;
    }
    .devImg{
        text-align: center;
        border-right: 1px gray dotted;
        // background: lightblue;
    }
}

</style>
